const express = require('express');
const router = express.Router();


/**
 * 封装的 COS-SDK 初始化函数，建议在服务启动时挂载全局，通过 this.cos 使用对象
 */
async function initcos() {
    const COS = require('cos-nodejs-sdk-v5')
    const res = await call({
        url: 'http://api.weixin.qq.com/_/cos/getauth',
        method: 'GET'
    })
    try {
        const info = JSON.parse(res)
        const auth = {
            TmpSecretId: info.TmpSecretId,
            TmpSecretKey: info.TmpSecretKey,
            SecurityToken: info.Token,
            ExpiredTime: info.ExpiredTime
        }
        this.cos = new COS({
            getAuthorization: async function (options, callback) {
                callback(auth)
            }
        })
        console.log('COS初始化成功')
    } catch (e) {
        console.log('COS初始化失败', res)
    }
}

/**
 * 封装的网络请求方法
 */
function call(obj) {
    return new Promise((resolve, reject) => {
        request({
            url: obj.url,
            method: obj.method || 'POST',
            headers: {
                'content-type': 'application/json'
            },
            body: JSON.stringify(obj.data || {})
        }, function (err, response) {
            if (err) reject(err)
            resolve(response.body)
        })
    })
}
